<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blogs/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blogs/images/apple-touch-icon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/blogs/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/blogs/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/blogs/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Node.js," />










<meta name="description" content="Express中的JWT身份认证1.JWT认证机制 为什么要使用JWT?  上一篇文章写得很详细，由于Session认证存在局限性，所以jwt应运而生。那session认证机制存在什么问题呢？ 1.session需要配合cookie来实现， 2.由于cookie不支持跨域访问，所以涉及到前端跨域请求后端的时候，需要做很多额外的配置，才能实现跨域session认证。  什么是JWT  JWT(JSO">
<meta property="og:type" content="article">
<meta property="og:title" content="Express中的JWT身份认证">
<meta property="og:url" content="https://louchaoyy.gitee.io/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/index.html">
<meta property="og:site_name" content="Chao&#39;s blog">
<meta property="og:description" content="Express中的JWT身份认证1.JWT认证机制 为什么要使用JWT?  上一篇文章写得很详细，由于Session认证存在局限性，所以jwt应运而生。那session认证机制存在什么问题呢？ 1.session需要配合cookie来实现， 2.由于cookie不支持跨域访问，所以涉及到前端跨域请求后端的时候，需要做很多额外的配置，才能实现跨域session认证。  什么是JWT  JWT(JSO">
<meta property="og:locale">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic1.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic2.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic3.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic4.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic5.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic6.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic7.png">
<meta property="article:published_time" content="2022-04-28T13:43:17.000Z">
<meta property="article:modified_time" content="2022-04-28T15:08:09.175Z">
<meta property="article:author" content="Chaoyxy">
<meta property="article:tag" content="Node.js">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://louchaoyy.gitee.io/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://louchaoyy.gitee.io/blogs/2022/04/28/Express中的JWT身份认证/"/>





  <title>Express中的JWT身份认证 | Chao's blog</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blogs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chao's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blogs/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://louchaoyy.gitee.io/blogs/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blogs/images/cat.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chao's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Express中的JWT身份认证</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-04-28T21:43:17+08:00">
                2022-04-28
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2022/04/28/Express中的JWT身份认证/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Express中的JWT身份认证"><a href="#Express中的JWT身份认证" class="headerlink" title="Express中的JWT身份认证"></a>Express中的JWT身份认证</h1><h2 id="1-JWT认证机制"><a href="#1-JWT认证机制" class="headerlink" title="1.JWT认证机制"></a>1.JWT认证机制</h2><ul>
<li>为什么要使用JWT?</li>
</ul>
<p>上一篇文章写得很详细，由于Session认证存在局限性，所以jwt应运而生。那session认证机制存在什么问题呢？</p>
<p>1.session需要配合cookie来实现，</p>
<p>2.由于cookie不支持跨域访问，所以涉及到前端跨域请求后端的时候，需要做很多额外的配置，才能实现跨域session认证。</p>
<ul>
<li>什么是JWT</li>
</ul>
<p>JWT(JSON WEB TOKEN)是目前最流行的跨域认证方案</p>
<ul>
<li>jwt认证的工作原理如下图所示：</li>
</ul>
<img src="/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic1.png" class title="jwt认证的工作原理">

<p>用户的信息通过Token字符串的形式，保存咋客户端浏览器中，服务器通过还原Token字符串的形式来认证用户的身份。</p>
<h2 id="2-JWT的组成部分"><a href="#2-JWT的组成部分" class="headerlink" title="2.JWT的组成部分"></a>2.JWT的组成部分</h2><p>jwt通常由三部分组成，分别是Header（头部）,Payload（有效荷载）,Signature（签名）</p>
<p>示意图如下：</p>
<img src="/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic2.png" class title="token的组成部分">

<p>其中：</p>
<ol>
<li>Payload部分才是真正的用户信息，他是用户信息经过加密之后生成的字符串</li>
<li>Header和Signature是安全性相关的部分，只是为了保证Token的安全性</li>
</ol>
<p>如下：</p>
<img src="/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic3.png" class title="token的组成部分">

<h2 id="3-JWT的使用方式"><a href="#3-JWT的使用方式" class="headerlink" title="3.JWT的使用方式"></a>3.JWT的使用方式</h2><p>客户端收到服务器返回的JWT之后，通常会将他存储在localstorage或者sessionStorage中</p>
<span id="more"></span>

<p>此后，客户端每次与服务端通信，都要带上这个给JWT的字符串，从而进行身份认证，推荐的做法是把JWT放在请求头的Authorization字段中，格式如下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Authorization:Bearer &lt;token&gt;</span><br></pre></td></tr></table></figure>

<h2 id="4-服务器如何生成JWT？"><a href="#4-服务器如何生成JWT？" class="headerlink" title="4.服务器如何生成JWT？"></a>4.服务器如何生成JWT？</h2><p><strong>需要安装两个包</strong></p>
<p>jsonwebtoken用于生成JWT字符串</p>
<p>express-jwt用于将JWT字符串解析还原成JSON对象</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">npm install jsonwebtoken --save</span><br><span class="line">npm install express-jwt --save</span><br></pre></td></tr></table></figure>

<p><strong>定义secret密钥</strong></p>
<p>为了保证JWT字符串的安全性，防止JWT字符串在网络传输过程中被别人破解，我们专门定义一个用于加密和解密的secret密钥</p>
<ol>
<li><p>当生成JWT字符串的时候，使用secret蜜月对用户信息进行加密，最终得到加密好的JWT字符串</p>
</li>
<li><p>当把JWT字符串解析还原成JSON对象的时候，需要使用secret密钥进行解密</p>
<p>格式如下，右边是一个字符串，越复杂越好，甚至可以通过某个字符串继续加密得到</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> secretKey = <span class="string">&#x27;chaoyxy&amp;_^_^&amp;*&amp;&#x27;</span></span><br></pre></td></tr></table></figure></li>
</ol>
<p><strong>如下，在登陆成功后生成JWT字符串</strong></p>
<p>使用jsonwebtoken提供的sign()方法，将用户的信息加密成JWT字符串，响应给客户端。</p>
<p>sign()方法有三个参数，分别是用户的<strong>信息对象，加密密钥，配置对象</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// jsonwebtoken</span></span><br><span class="line"><span class="keyword">const</span> jwt = <span class="built_in">require</span>(<span class="string">&#x27;jsonwebtoken&#x27;</span>);</span><br><span class="line"><span class="comment">// 解析jwt</span></span><br><span class="line"><span class="keyword">const</span> &#123; expressjwt &#125; = <span class="built_in">require</span>(<span class="string">&#x27;express-jwt&#x27;</span>);</span><br><span class="line"><span class="comment">// 登录生成jwt</span></span><br><span class="line">router.post(<span class="string">&#x27;/login&#x27;</span>,<span class="function">(<span class="params">req,res</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(req.body.username!==<span class="string">&#x27;admin&#x27;</span>||req.body.password!==<span class="string">&#x27;chao3210.&#x27;</span>)&#123;</span><br><span class="line">        res.send(&#123;</span><br><span class="line">            <span class="attr">status</span>:<span class="number">0</span>,</span><br><span class="line">            <span class="attr">msg</span>:<span class="string">&quot;登录失败&quot;</span></span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        res.send(&#123;</span><br><span class="line">            <span class="attr">status</span>:<span class="number">200</span>,</span><br><span class="line">            <span class="attr">msg</span>:<span class="string">&quot;登录成功&quot;</span>,</span><br><span class="line">            <span class="comment">// sign三个参数，分别是用户的信息对象，加密密钥，配置对象(token有效期：30s)**</span></span><br><span class="line">            <span class="attr">token</span>:jwt.sign(&#123;<span class="attr">username</span>:req.body.username,&#125;,secretKey,&#123;<span class="attr">expiresIn</span>:<span class="string">&#x27;30s&#x27;</span>&#125;)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>结果如下图：</p>
<img src="/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic4.png" class title="登录成功获取token">

<p><strong>将JWT还原成JSON对象</strong></p>
<p>客户端在每次访问那些有权限接口的时候，都需要主动通过请求头中的Authorization字段，将Token字符串发送到服务器进行身份认证，此时，服务器可以用过express-jwt这个中间件，自动将客户端发送过来的Token解析还原成JSON对象</p>
<p>使用方法，直接使用app.use()去注册</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// expressjwt(&#123;secret:secretKey,algorithms:[&#x27;HS256&#x27;]&#125;就是用来解析token的中间件</span></span><br><span class="line"><span class="comment">// unless(&#123;path:[/^\/api\//]&#125;)用来指定哪些端口不需要访问权限</span></span><br><span class="line">app.use(expressjwt(&#123;<span class="attr">secret</span>:secretKey,<span class="attr">algorithms</span>:[<span class="string">&#x27;HS256&#x27;</span>]&#125;).unless(&#123;<span class="attr">path</span>:[<span class="regexp">/^\/api\//</span>]&#125;))</span><br></pre></td></tr></table></figure>

<p>在新版本中，需要在第一个参数中配置**algorithms:[‘HS256’]**，加密方式，具体可以见官方文档</p>
<img src="/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic5.png" class title="express-jwt官方截图">

<p>附上链接：<a target="_blank" rel="noopener" href="https://www.npmjs.com/package/express-jwt">https://www.npmjs.com/package/express-jwt</a></p>
<p><strong>新版本中，可以在需要权限的接口中使用req.auth去获取到通过解密之后的用户信息</strong></p>
<p><strong>配置了express-jwt中间件之后，会自动把用户信息挂载到req.auth上，我们可以在路由的任何地方拿到req.auth值</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 在需要访问权限的接口中查看解密的用户信息</span></span><br><span class="line">app.get(<span class="string">&#x27;/getinfo&#x27;</span>,<span class="function">(<span class="params">req,res</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(req.auth);</span><br><span class="line">    res.send(&#123;</span><br><span class="line">        <span class="attr">status</span>:<span class="number">200</span>,</span><br><span class="line">        <span class="attr">msg</span>:<span class="string">&quot;请求成功&quot;</span>,</span><br><span class="line">        <span class="attr">auth</span>:req.auth</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>结果为</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;status&quot;</span>: <span class="number">200</span>,</span><br><span class="line">    <span class="attr">&quot;msg&quot;</span>: <span class="string">&quot;请求成功&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;auth&quot;</span>: &#123;</span><br><span class="line">        <span class="attr">&quot;username&quot;</span>: <span class="string">&quot;admin&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;iat&quot;</span>: <span class="number">1651157968</span>,</span><br><span class="line">        <span class="attr">&quot;exp&quot;</span>: <span class="number">1651157998</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>效果如下：</p>
<img src="/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic6.png" class title="在需要访问权限的接口中查看解密的用户信息">

<p><strong>如果Token过期的，通过配置错误级中间件可以很友好的提示用户</strong></p>
<p>错误级中间件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">app.use(<span class="function">(<span class="params">err, req, res, next</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Error:&#x27;</span> + err.message);</span><br><span class="line">    <span class="keyword">if</span>(err.name===<span class="string">&#x27;UnauthorizedError&#x27;</span>)&#123;</span><br><span class="line">        res.send(&#123;</span><br><span class="line">            <span class="attr">status</span>:<span class="number">501</span>,</span><br><span class="line">            <span class="attr">msg</span>:<span class="string">&quot;token已过期&quot;</span></span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    res.send(<span class="string">&#x27;Error:&#x27;</span> + err.message);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>结果如下：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;status&quot;</span>: <span class="number">501</span>,</span><br><span class="line">    <span class="attr">&quot;msg&quot;</span>: <span class="string">&quot;token已过期&quot;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>通过**<code>err.name</code>**可以很方便的拿到错误类型的名字</p>
<p>效果如下：</p>
<img src="/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/pic7.png" class title="token已过期">

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="http://chaoyxy.cn/data/User/admin/home/desktop/images/alipay.jpg" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="http://chaoyxy.cn/data/User/admin/home/desktop/images/wechatpay.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blogs/tags/Node-js/" rel="tag"># Node.js</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blogs/2022/04/28/Express%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/" rel="next" title="Express身份认证">
                <i class="fa fa-chevron-left"></i> Express身份认证
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/" rel="prev" title="express脚手架与路由模块化">
                express脚手架与路由模块化 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a target="_blank" rel="noopener" href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blogs/images/cat.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blogs/archives">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blogs/tags/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/louchaoyy" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-gitee"></i>Gitee</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="louchao@louchaoyy.cn" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81"><span class="nav-number">1.</span> <span class="nav-text">Express中的JWT身份认证</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-JWT%E8%AE%A4%E8%AF%81%E6%9C%BA%E5%88%B6"><span class="nav-number">1.1.</span> <span class="nav-text">1.JWT认证机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-JWT%E7%9A%84%E7%BB%84%E6%88%90%E9%83%A8%E5%88%86"><span class="nav-number">1.2.</span> <span class="nav-text">2.JWT的组成部分</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-JWT%E7%9A%84%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F"><span class="nav-number">1.3.</span> <span class="nav-text">3.JWT的使用方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%A6%82%E4%BD%95%E7%94%9F%E6%88%90JWT%EF%BC%9F"><span class="nav-number">1.4.</span> <span class="nav-text">4.服务器如何生成JWT？</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Chaoyxy</span>

  
</div>

<span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.3</div>
-->




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blogs/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/blogs/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/blogs/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/blogs/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/blogs/js/src/bootstrap.js?v=5.1.3"></script>



  


  

    
      <script id="dsq-count-scr" src="https://Chaoyxy.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'https://louchaoyy.gitee.io/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/';
          this.page.identifier = '2022/04/28/Express中的JWT身份认证/';
          this.page.title = 'Express中的JWT身份认证';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://Chaoyxy.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  





  

  

  

  
  

  

  

  

</body>
</html>
